import os
import urllib
import logging

import TorrentFinder
import CollectionScanner
import RTorrentXMLRPC

class Library(object):
  def __init__(self, path):
    self.files = list(CollectionScanner.scan(path)) 

  def __contains__(self, item):
    return item in self.files

  @property
  def all_series(self):
    return set(f.series_name.lower() for f in self.files)

def suggest_downloads(library_path, tpb_page, rtorrent_xmlrpc):
  logger = logging.getLogger('tiger.TorrentResolver.suggest_downloads')
  rtorrent_interface = RTorrentXMLRPC.RTorrentInterface(rtorrent_xmlrpc)

  library = Library(library_path)
  logger.info('know %d series', len(library.all_series))
  #current_downloads = rtorrent_interface.active_downloads()
  #logger.info('%d active downloads', len(current_downloads))
  current_downloads = []
  possible_downloads = TorrentFinder.get_tpb_data(tpb_page)
  logger.info('%d new candidates', len(possible_downloads))

  #Ignorelist
  try:
    ignore_file = open('ignore_series')
    ignore_list = [l.strip() for l in ignore_file]
    ignore_file.close()
    logger.info("Loaded %d series to ignore", len(ignore_list))
  except IOError:
    logger.info("No ignore file present")
    ignore_list = []

  likely_downloads = []
  logger.debug(ignore_list)
  for pd in possible_downloads:
    logger.debug("Possible: %s", pd)
    if pd.series_name not in ignore_list:
      if pd.series_name in library.all_series:
        if pd not in library:
          if pd not in current_downloads:
	    if pd in likely_downloads:
	      old = likely_downloads.pop(likely_downloads.index(pd))
	      if pd.seeds > old.seeds:
	        # Replace with newer, better candidate
	        likely_downloads.append(pd)
	        logger.debug("    Replacing %s with %s", old, pd)
	      else:
	        likely_downloads.append(old)
            else:
	      likely_downloads.append(pd)
	  else:
	    logger.debug("    Reject as downloading")
        else:
          logger.debug("    Reject as already have")
      else:
        logger.debug("    Reject series")
    else:
      logger.debug("    Reject as ignored")

  return likely_downloads

def getTigerLogger(path):
  #Set up logger
  logger = logging.getLogger(path)
  logger.setLevel(logging.DEBUG)
  formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
  ch = logging.StreamHandler()
  ch.setLevel(logging.DEBUG)
  ch.setFormatter(formatter)
  logger.addHandler(ch)
  return logger

def main():
  path = '/media/storage/video/series'
  #page = open('tpb.html')
  page = urllib.urlopen('http://thepiratebay.org/top/205')
  #page = urllib.urlopen('http://thepiratebay.org/tv/1112/S04/')
  rtorrent_xmlrpc = 'http://mythtv/RPC2'

  ld = suggest_downloads(path, page, rtorrent_xmlrpc)
  print
  for d in ld:
    print d, '-->', d.url

if __name__ == "__main__":
  logger = getTigerLogger('tiger.TorrentResolver')
  main()
